#include "CMQTTClient.h"
//#include <Windows.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <string.h>

//#define ADDRESS "tcp://192.168.11.27:1883"
#define ADDRESS "tcp://gosuncn.kinghowe.cn:1883"
#define TOPIC "ngrokserver/test"
#define CLIENTID "localhostSub"
#define PAYLOAD     "Hello World*****"
#define QOS         1
#define TIMEOUT     10000L

using namespace std;

void delivered(void *context, MQTTClient_deliveryToken dt)
{
	printf("Message with token value %d delivery confirmed\n", dt);
}

int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
	int i;
	char* payloadptr;

	printf("Message arrived\n");
	printf("     topic: %s\n", topicName);
	printf("   message: ");

	payloadptr = (char*)message->payload;
	for (i = 0; i < message->payloadlen; i++)
	{
		putchar(*payloadptr++);
	}
	putchar('\n');
	MQTTClient_freeMessage(&message);
	MQTTClient_free(topicName);
	return 1;
}

void connlost(void *context, char *cause)
{
	printf("\nConnection lost\n");
	printf("     cause: %s\n", cause);
}

int main()
{
	CMQTTClent client;
	client.conf.address = ADDRESS;
	client.conf.clientID = CLIENTID;
	client.conf.qos = QOS;
	client.conf.topic = TOPIC;
	client.conf.timeout = TIMEOUT;
	client.conf.type = PUBLISH;
	//client.conf.type = SUBSCRIBE;
	client.conf.keepAliveInterval = 20;
	client.conf.cleanSession = 1;
	client.conf.connlostCB = &connlost;
	client.conf.deliverycompleteCB = &delivered;
	client.conf.msgCB = &msgarrvd;
	client.conf.context = nullptr;

	client.init();
	while (1) {
		client.publish(PAYLOAD, (int)strlen(PAYLOAD), 0);
		sleep(5);
	}

	//client.startSub();

	getchar();

	client.mqttDestory();

	return 0;

}